﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace LL3D
{
    public class GameScreen
    {
        //Variaveis que representam os objetos
        Model Nave;
        Model solo;
        Model ceu;
        //------------------------------------        

        //Variaveis para o movimento da nave------------------------------------
        float posicaoX;
        float posicaoY;
        float vx; //Velocidade no eixo x
        float vy; //Velocidade no eixo y
        const float upAy = 0.0005f; //Aceleracao para cima no eixo y
        const float downAy = -0.0001f; //Aceleracao para baixo no eixo y 
        int combustivel;
        //----------------------------------------------------------------------

        //Variaveis para desenhar o solo e o ceu--------------------------------
        DualTextureEffect soloLunar;
        DualTextureEffect ceuEstrelas;

        //----------------------------------------------------------------------

        //HUD---------------------------------
        SpriteFont fonte;
        string vely;
        string posy;
        int score;
        //------------------------------------

        GraphicsDevice gd;

        public GameScreen(ContentManager Content, GraphicsDevice graphicsDevice)
        {

            //Carregando os objetos que aparecerao na tela de jogo-----------------------
            Nave = Content.Load<Model>("Caixa");
            solo = Content.Load<Model>("plano");
            ceu = Content.Load<Model>("plano");
            soloLunar = new DualTextureEffect(graphicsDevice);//desenhador/pintador 3D
            soloLunar.Texture = Content.Load<Texture2D>("chao");
            soloLunar.Texture2 = Content.Load<Texture2D>("chao");
            ceuEstrelas = new DualTextureEffect(graphicsDevice);//desenhador/pintador 3D
            ceuEstrelas.Texture = Content.Load<Texture2D>("estrelas");
            ceuEstrelas.Texture2 = Content.Load<Texture2D>("estrelas");

            fonte = Content.Load<SpriteFont>("gameFont");
            //---------------------------------------------------------------------------

            //Setando as variaveis para o movimento da nave
            posicaoX = 0;
            posicaoY = 8;
            vx = 0.01f;
            vy = -0.04f;
            combustivel = 5000;
            score = 0;
            //---------------------------------------------

            gd = graphicsDevice;
        }

        //float RESETvy()
        //{
        //    vy += downAy;
        //    return vy = -0.04f;
        //}

        public void Update()
        {
            KeyboardState keyState = Keyboard.GetState();

            posicaoY += vy; //Efeito gravidade

            //Movimentacao da nave na vertical------------------------------------------------
            if (keyState.IsKeyDown(Keys.W) && combustivel > 0)
            {
                combustivel -= 20;
                if (vy < 0.02)
                    vy += upAy + downAy;
                else
                {
                    vy = 0.02f;
                }
                //if (keyState.IsKeyDown(Keys.W) //&& vy > -0.01f)
                //{
                //    vy = -0.01f;   Esse pedaco serve so para reduzir a velocidade no eixo y
                //}
            }
            else
            {
                vy += downAy;
            }
            //-------------------------------------------------------------------------------

            //Movimentacao horizontal--------------------------
            if (keyState.IsKeyDown(Keys.D) && posicaoY > -11 && combustivel > 0)
            {
                posicaoX += vx;
            }
            else if (keyState.IsKeyDown(Keys.A) && posicaoY > -11 && combustivel > 0)
            {
                posicaoX -= vx;
            }
            //--------------------------------------------------

            //Colisão com o chao--------------------------------
            if (posicaoY < -11 && vy > -0.05)
            {
                posicaoY = -11;
                vy = 0;
                vx = 0;
                score = combustivel;
            }//--------------------------------------------------
            else if (posicaoY < -11)
            {
                Game1.telaAtual = 4;
            }
            //Quando o combustivel acabar------------------------
            if (combustivel < 0)
            {
                combustivel = 0;
                vy = 0;
                vx = 0;
            }//--------------------------------------------------

        }

        public void Draw(SpriteBatch spritebatch)
        {
            //Colocando uma textura no cubo--------------------------------
            //BasicEffect effect = Nave.Meshes[0].Effects[0] as BasicEffect;
            //effect.TextureEnabled = true;
            //effect.Texture = 
            //-------------------------------------------------------------

            //effect.Texture = player.GetTexture();

            //pos representa a posicao da nave no espaco--
            Vector3 pos = new Vector3(posicaoX, posicaoY, 0);
            //--------------------------------------------

            Matrix view = Matrix.CreateLookAt(
                new Vector3(0, 0, 30),//posicao
                new Vector3(0, 0, 0),//apontamento
                Vector3.Up);//'cima'

            Matrix proj = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4,//abertura '45'
                (float)(16 / 9),//GraphicsDevice.Viewport.AspectRatio,//largura/altura
                //graphics.PreferredBackBufferWidth/graphics.PreferredBackBufferHeight,
                1.0f,//near
                1000.0f);//far

            //Desenhando o ceu-----------------------------------------
            ceuEstrelas.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4,
                gd.Viewport.AspectRatio,
                1.0f,
                100.0f);

            DrawModel(
                solo,
                Matrix.CreateTranslation(0, 0, -10)*Matrix.CreateRotationX(MathHelper.ToRadians(90)) * Matrix.CreateScale(2f),
                ceuEstrelas);

            ceuEstrelas.View = Matrix.CreateLookAt(
                new Vector3(0, 10, 40),
                new Vector3(0, 15, 0),
                Vector3.Up);
            //-----------------------------------------------------------
            
            //Desenhando o solo lunar------------------------------------
            soloLunar.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4,
                gd.Viewport.AspectRatio,
                1.0f,
                100.0f);

            DrawModel(
                solo,
                Matrix.CreateTranslation(0, 0, -10),
                soloLunar);

            soloLunar.View = Matrix.CreateLookAt(
                new Vector3(0, 3, 40),
                new Vector3(0, 15, 0),
                Vector3.Up);
            //-----------------------------------------------------------

            //Desenhando a nave------------------------------------------
            Nave.Draw(
                Matrix.CreateTranslation(pos),
                view,
                proj);
            //-----------------------------------------------------------
            
            spritebatch.Begin();
            //Velocidade
            spritebatch.DrawString(fonte, "Velocidade: ", new Vector2(0, 60), Color.White);
            spritebatch.DrawString(fonte, vely = String.Format("{0:n}", Math.Abs(vy)), new Vector2(0, 80), Color.White);
            spritebatch.DrawString(fonte, "Km/s", new Vector2(58, 80), Color.White);
            //Altura
            spritebatch.DrawString(fonte, "Altura: ", new Vector2(0, 100), Color.White);
            spritebatch.DrawString(fonte, posy = String.Format("{0:n}", (posicaoY+11)), new Vector2(0, 120), Color.White);
            spritebatch.DrawString(fonte, "Km", new Vector2(60, 120), Color.White);
            //Combustivel
            spritebatch.DrawString(fonte, "Combustivel: ", new Vector2(0, 140), Color.White);
            spritebatch.DrawString(fonte, combustivel.ToString(), new Vector2(0, 160), Color.White);
            spritebatch.DrawString(fonte, "Litros", new Vector2(50, 160), Color.White);
            //Score
            spritebatch.DrawString(fonte, "Pontuacao: ", new Vector2(0, 0), Color.White);
            spritebatch.DrawString(fonte, score.ToString(), new Vector2(0, 20), Color.White);
            spritebatch.End();
        }

        //Funcao usada para desenhar o modelo na tela------------------------------------
        private void DrawModel(Model m, Matrix world, DualTextureEffect be)
        {
            foreach (ModelMesh mm in m.Meshes)
            {
                foreach (ModelMeshPart mmp in mm.MeshParts)
                {
                    be.World = world;
                    gd.SetVertexBuffer(mmp.VertexBuffer, mmp.VertexOffset);
                    gd.Indices = mmp.IndexBuffer;
                    be.CurrentTechnique.Passes[0].Apply();
                    gd.DrawIndexedPrimitives(
                        PrimitiveType.TriangleList, 0, 0,
                        mmp.NumVertices, mmp.StartIndex, mmp.PrimitiveCount);
                }

            }
        }
        //---------------------------------------------------------------------------------
    }
}
